//
//  LocationFetcher.swift
//  Tala
//
//  Created by 千策万划-mini on 2025/5/22.
//

import CoreLocation
import Foundation

class LocationFetcher: NSObject, CLLocationManagerDelegate {
    // MARK: - Properties
    private var locationManager: CLLocationManager
    private var completion: ((CLLocationCoordinate2D?) -> Void)?
    private var timeoutTimer: Timer?
    
    // 本地存储的键
    private let lastLocationKey = "LastLocation"
    
    // MARK: - Initialization
    override init() {
        locationManager = CLLocationManager()
        super.init()
        
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.distanceFilter = 10
    }
    
    // MARK: - Public Methods
    func fetchLocation(completion: @escaping (CLLocationCoordinate2D?) -> Void) {
        self.completion = completion
        
        // 检查定位权限
        let status = locationManager.authorizationStatus
        switch status {
        case .notDetermined:
            locationManager.requestWhenInUseAuthorization()
        case .authorizedWhenInUse, .authorizedAlways:
            startLocationUpdate()
        default:
            // 如果无法获取定位，返回本地存储的位置
            completion(getLastLocation())
            cleanup()
        }
        
        // 设置超时
        timeoutTimer = Timer.scheduledTimer(withTimeInterval: 6.0, repeats: false) { [weak self] _ in
            self?.handleTimeout()
        }
    }
    
    // MARK: - Private Methods
    private func startLocationUpdate() {
        locationManager.startUpdatingLocation()
    }
    
    private func handleTimeout() {
        // 超时时返回本地存储的位置
        completion?(getLastLocation())
        cleanup()
    }
    
    private func cleanup() {
        locationManager.stopUpdatingLocation()
        timeoutTimer?.invalidate()
        timeoutTimer = nil
        completion = nil
    }
    
    // 保存位置信息到本地
    private func saveLocation(_ coordinate: CLLocationCoordinate2D) {
        let locationDict: [String: Double] = [
            "latitude": coordinate.latitude,
            "longitude": coordinate.longitude
        ]
        UserDefaults.standard.set(locationDict, forKey: lastLocationKey)
    }
    
    // 获取本地存储的位置信息
    private func getLastLocation() -> CLLocationCoordinate2D? {
        guard let locationDict = UserDefaults.standard.dictionary(forKey: lastLocationKey) as? [String: Double],
              let latitude = locationDict["latitude"],
              let longitude = locationDict["longitude"] else {
            return nil
        }
        
        return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
    
    // MARK: - CLLocationManagerDelegate
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        
        // 保存新的位置信息
        saveLocation(location.coordinate)
        
        completion?(location.coordinate)
        cleanup()
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Location update failed: \(error.localizedDescription)")
        // 定位失败时返回本地存储的位置
        completion?(getLastLocation())
        cleanup()
    }
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        let status = manager.authorizationStatus
        switch status {
        case .authorizedWhenInUse, .authorizedAlways:
            startLocationUpdate()
        default:
            // 权限被拒绝时返回本地存储的位置
            completion?(getLastLocation())
            cleanup()
        }
    }
    
    deinit {
        cleanup()
    }
}
